from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from models.safety import SafetyInspection, SafetyIncident
from extensions import db
from datetime import datetime
import uuid

safety_bp = Blueprint('safety', __name__)

@safety_bp.route('/inspections')
@login_required
def inspection_list():
    # 获取查询参数
    product_name = request.args.get('product_name', '')
    batch_number = request.args.get('batch_number', '')
    inspection_type = request.args.get('inspection_type', '')
    result = request.args.get('result', '')
    
    # 构建查询
    query = SafetyInspection.query
    if product_name:
        query = query.filter(SafetyInspection.product_name.like(f'%{product_name}%'))
    if batch_number:
        query = query.filter(SafetyInspection.batch_number.like(f'%{batch_number}%'))
    if inspection_type:
        query = query.filter(SafetyInspection.inspection_type == inspection_type)
    if result:
        query = query.filter(SafetyInspection.result == result)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(SafetyInspection.inspection_date.desc()).paginate(
        page=page, per_page=10, error_out=False)
    
    return render_template('safety/inspection_list.html',
                         inspections=pagination.items,
                         pagination=pagination,
                         product_name=product_name,
                         batch_number=batch_number,
                         inspection_type=inspection_type,
                         result=result)

@safety_bp.route('/inspections/add', methods=['GET', 'POST'])
@login_required
def inspection_add():
    if request.method == 'POST':
        inspection = SafetyInspection(
            inspection_no=f"INS{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:8]}",
            product_name=request.form.get('product_name'),
            batch_number=request.form.get('batch_number'),
            inspection_type=request.form.get('inspection_type'),
            inspector=request.form.get('inspector'),
            inspection_date=datetime.strptime(request.form.get('inspection_date'), '%Y-%m-%dT%H:%M'),
            temperature=float(request.form.get('temperature')) if request.form.get('temperature') else None,
            humidity=float(request.form.get('humidity')) if request.form.get('humidity') else None,
            result=request.form.get('result'),
            issues_found=request.form.get('issues_found'),
            recommendations=request.form.get('recommendations'),
            next_inspection_date=datetime.strptime(request.form.get('next_inspection_date'), '%Y-%m-%d') if request.form.get('next_inspection_date') else None,
            created_by=current_user.id,
            notes=request.form.get('notes')
        )
        db.session.add(inspection)
        db.session.commit()
        flash('安全检查记录创建成功', 'success')
        return redirect(url_for('safety.inspection_list'))
    return render_template('safety/inspection_add.html')

@safety_bp.route('/inspections/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def inspection_edit(id):
    inspection = SafetyInspection.query.get_or_404(id)
    if request.method == 'POST':
        inspection.product_name = request.form.get('product_name')
        inspection.batch_number = request.form.get('batch_number')
        inspection.inspection_type = request.form.get('inspection_type')
        inspection.inspector = request.form.get('inspector')
        inspection.inspection_date = datetime.strptime(request.form.get('inspection_date'), '%Y-%m-%dT%H:%M')
        inspection.temperature = float(request.form.get('temperature')) if request.form.get('temperature') else None
        inspection.humidity = float(request.form.get('humidity')) if request.form.get('humidity') else None
        inspection.result = request.form.get('result')
        inspection.issues_found = request.form.get('issues_found')
        inspection.recommendations = request.form.get('recommendations')
        inspection.next_inspection_date = datetime.strptime(request.form.get('next_inspection_date'), '%Y-%m-%d') if request.form.get('next_inspection_date') else None
        inspection.notes = request.form.get('notes')
        
        db.session.commit()
        flash('安全检查记录更新成功', 'success')
        return redirect(url_for('safety.inspection_list'))
    return render_template('safety/inspection_edit.html', inspection=inspection)

@safety_bp.route('/incidents')
@login_required
def incident_list():
    # 获取查询参数
    product_name = request.args.get('product_name', '')
    batch_number = request.args.get('batch_number', '')
    incident_type = request.args.get('incident_type', '')
    status = request.args.get('status', '')
    severity = request.args.get('severity', '')
    
    # 构建查询
    query = SafetyIncident.query
    if product_name:
        query = query.filter(SafetyIncident.product_name.like(f'%{product_name}%'))
    if batch_number:
        query = query.filter(SafetyIncident.batch_number.like(f'%{batch_number}%'))
    if incident_type:
        query = query.filter(SafetyIncident.incident_type == incident_type)
    if status:
        query = query.filter(SafetyIncident.status == status)
    if severity:
        query = query.filter(SafetyIncident.severity == severity)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(SafetyIncident.occurrence_date.desc()).paginate(
        page=page, per_page=10, error_out=False)
    
    return render_template('safety/incident_list.html',
                         incidents=pagination.items,
                         pagination=pagination,
                         product_name=product_name,
                         batch_number=batch_number,
                         incident_type=incident_type,
                         status=status,
                         severity=severity)

@safety_bp.route('/incidents/add', methods=['GET', 'POST'])
@login_required
def incident_add():
    if request.method == 'POST':
        incident = SafetyIncident(
            incident_no=f"INC{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:8]}",
            incident_type=request.form.get('incident_type'),
            severity=request.form.get('severity'),
            product_name=request.form.get('product_name'),
            batch_number=request.form.get('batch_number'),
            occurrence_date=datetime.strptime(request.form.get('occurrence_date'), '%Y-%m-%dT%H:%M'),
            discovery_date=datetime.strptime(request.form.get('discovery_date'), '%Y-%m-%dT%H:%M'),
            location=request.form.get('location'),
            description=request.form.get('description'),
            immediate_action=request.form.get('immediate_action'),
            created_by=current_user.id,
            notes=request.form.get('notes')
        )
        db.session.add(incident)
        db.session.commit()
        flash('安全事故记录创建成功', 'success')
        return redirect(url_for('safety.incident_list'))
    return render_template('safety/incident_add.html')

@safety_bp.route('/incidents/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def incident_edit(id):
    incident = SafetyIncident.query.get_or_404(id)
    if request.method == 'POST':
        incident.incident_type = request.form.get('incident_type')
        incident.severity = request.form.get('severity')
        incident.product_name = request.form.get('product_name')
        incident.batch_number = request.form.get('batch_number')
        incident.occurrence_date = datetime.strptime(request.form.get('occurrence_date'), '%Y-%m-%dT%H:%M')
        incident.discovery_date = datetime.strptime(request.form.get('discovery_date'), '%Y-%m-%dT%H:%M')
        incident.location = request.form.get('location')
        incident.description = request.form.get('description')
        incident.immediate_action = request.form.get('immediate_action')
        incident.root_cause = request.form.get('root_cause')
        incident.corrective_action = request.form.get('corrective_action')
        incident.status = request.form.get('status')
        incident.resolved_date = datetime.strptime(request.form.get('resolved_date'), '%Y-%m-%d') if request.form.get('resolved_date') else None
        incident.handler_id = current_user.id
        incident.notes = request.form.get('notes')
        
        db.session.commit()
        flash('安全事故记录更新成功', 'success')
        return redirect(url_for('safety.incident_list'))
    return render_template('safety/incident_edit.html', incident=incident) 